<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="请选择题型" clearable>
          <el-option
            v-for="dict in dict.type.bis_question_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="难度" prop="difficulty">
        <el-select v-model="queryParams.difficulty" placeholder="请选择难度" clearable>
          <el-option
            v-for="dict in dict.type.bis_question_difficulty"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <input-and-search-with-tree
          v-model="queryParams.categoryId"
          @change="handleCategoryChange"
        />
      </el-form-item>
      <el-form-item label="创建者" prop="createName">
        <el-input
          v-model="queryParams.createName"
          placeholder="请输入创建者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['question.js:questions:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['question.js:questions:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['question.js:questions:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['question.js:questions:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 卡片式布局 -->
    <div class="question-cards-container">
      <el-card
        v-for="question in questionsList"
        :key="question.questionId"
        class="question-card"
        shadow="hover"
        @click.native="handleCardClick(question)"
      >
        <div slot="header" class="question-title">
          <span>{{ question.questionTitle || '无标题' }}</span>
          <div class="question-meta">
            <dict-tag
              :options="dict.type.bis_question_type"
              :value="question.questionType"
              size="small"
            />
            <dict-tag
              :options="dict.type.bis_question_difficulty"
              :value="question.difficulty"
              size="small"
            />
          </div>
        </div>
        <div class="question-content" v-html="truncateQuestionText(question.questionText)"></div>
        <div class="question-footer">
          <span class="category">{{ question.categoryName || '未分类' }}</span>
          <span class="create-info">
            {{ question.createName }} · {{ parseTime(question.createTime, '{y}-{m}-{d}') }}
          </span>
        </div>
      </el-card>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 题目详情弹窗 -->
    <el-dialog
      title="题目详情"
      :visible.sync="detailVisible"
      width="800px"
      append-to-body
    >
      <question-detail :question="selectedRow" v-if="detailVisible" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
        <el-button
          type="primary"
          @click="handleEditDetail"
          v-hasPermi="['question.js:questions:edit']"
        >
          编辑
        </el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="1300px"
      append-to-body
      @closed="handleDialogClosed"
    >
      <question-input
        v-if="dialogVisible"
        :question-id="currentQuestionId"
        @success="handleQuestionSuccess"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listQuestions, delQuestions } from "@/api/question/manage";
import QuestionInput from './QuestionInput.vue';
import QuestionDetail from './QuestionDetail.vue';
import InputAndSearchWithTree from "@/components/InputAndSearchWithTree/index.vue";
import '@wangeditor/editor/dist/css/style.css'

export default {
  name: "QuestionList",
  components: {
    InputAndSearchWithTree,
    QuestionInput,
    QuestionDetail
  },
  dicts: ['bis_question_type', 'bis_question_difficulty'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      questionsList: [],
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        questionText: null,
        questionType: null,
        difficulty: null,
        categoryId: null,
        createdBy: null,
        createName: null,
        createTime: null,
        beginTime: null,
        endTime: null
      },
      // 详情相关
      detailVisible: false,
      selectedRow: null,
      // 编辑相关
      dialogVisible: false,
      dialogTitle: '',
      currentQuestionId: null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      this.queryParams.beginTime = this.dateRange[0];
      this.queryParams.endTime = this.dateRange[1];
      listQuestions(this.queryParams).then(response => {
        this.questionsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.questionId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.dialogTitle = '新增题目';
      this.currentQuestionId = null;
      this.dialogVisible = true;
    },
    handleUpdate(row) {
      const questionId = row?.questionId || this.ids[0];
      if (!questionId) return;

      this.dialogTitle = '编辑题目';
      this.currentQuestionId = questionId;
      this.dialogVisible = true;
    },
    handleDelete(row) {
      const questionIds = row?.questionId || this.ids;
      if (!questionIds.length) return;

      this.$confirm('是否确认删除题目?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delQuestions(questionIds);
      }).then(() => {
        this.getList();
        this.$message.success('删除成功');
      }).catch(() => {});
    },
    handleExport() {
      this.download('question/manage/export', {
        ...this.queryParams
      }, `questions_${new Date().getTime()}.xlsx`);
    },
    handleCategoryChange(node) {
      this.queryParams.categoryId = node ? node.categoryId : null;
    },
    // 卡片点击事件
    handleCardClick(question) {
      this.selectedRow = question;
      this.detailVisible = true;
    },
    // 编辑详情中的题目
    handleEditDetail() {
      this.dialogTitle = '编辑题目';
      this.currentQuestionId = this.selectedRow.questionId;
      this.dialogVisible = true;
      this.detailVisible = false;
    },
    // 处理题目操作成功
    handleQuestionSuccess() {
      this.dialogVisible = false;
      this.getList();
    },
    // 对话框关闭
    handleDialogClosed() {
      this.currentQuestionId = null;
    },
    // 截断题干文本
    truncateQuestionText(html) {
      if (!html) return '--';
      // 去除HTML标签
      const plainText = html.replace(/<[^>]+>/g, '');
      // 截断并添加省略号
      return plainText.length > 100
        ? plainText.substring(0, 100) + '...'
        : plainText;
    }
  }
};
</script>

<style scoped>
.question-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.question-card {
  cursor: pointer;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.question-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.question-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.question-meta {
  display: flex;
  gap: 8px;
}

.question-content {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  color: #666;
  line-height: 1.5;
}

.question-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  font-size: 12px;
  color: #999;
}

.category {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.create-info {
  align-self: flex-end;
}
</style>
